/*
 * Copyright 2023 yifeng Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yifeng.repo.flink.data.transport.relational.connection;

import com.yifeng.repo.flink.data.transport.config.DataSourceConfig;
import com.yifeng.repo.flink.data.transport.dto.DbTypeEnums;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

/** A connection pool factory to create pooled DataSource {@link HikariDataSource}. */
public class JdbcConnectionPoolFactory {

    public static final String CONNECTION_POOL_PREFIX = "connection-pool-";
    public static final String SERVER_TIMEZONE_KEY = "serverTimezone";
    public static final int MINIMUM_POOL_SIZE = 1;

    public HikariDataSource createPooledDataSource(DataSourceConfig sourceConfig) {
        final HikariConfig config = new HikariConfig();

        String hostName = sourceConfig.getHostname();
        int port = sourceConfig.getPort();

        config.setPoolName(CONNECTION_POOL_PREFIX + hostName + ":" + port);
        config.setJdbcUrl(getUrl(sourceConfig));
        config.setUsername(sourceConfig.getUsername());
        config.setPassword(sourceConfig.getPassword());
        config.setMinimumIdle(MINIMUM_POOL_SIZE);
        config.setMaximumPoolSize(sourceConfig.getConnectionPoolSize());
        config.setConnectionTimeout(sourceConfig.getConnectTimeout().toMillis());
        config.addDataSourceProperty(SERVER_TIMEZONE_KEY, sourceConfig.getServerTimeZone());
        config.setDriverClassName(sourceConfig.getDriverClassName());
        
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

        return new HikariDataSource(config);
    }

    private String getUrl(DataSourceConfig dataSourceConfig){
        String url = "";
        if(DbTypeEnums.MYSQL.getType().equals(dataSourceConfig.getDbType())) {
            url = DbConsts.MYSQL_HEAD+ dataSourceConfig.getHostname() + DbConsts.COLON + dataSourceConfig.getPort() + DbConsts.SINGLE_SLASH_RIGHT+ dataSourceConfig.getDatabase() + DbConsts.MYSQL_TAIL;
        } else if(DbTypeEnums.ORACLE.getType().equals(dataSourceConfig.getDbType())) {
            url = DbConsts.ORACLE_HEAD + dataSourceConfig.getHostname() + DbConsts.COLON + dataSourceConfig.getPort() + DbConsts.COLON + dataSourceConfig.getDatabase();
        }
        return url;
    }
}
